part of '../repository.dart';

BuiltMap<String, dynamic> _migrateBackupContentFromFirstVersionToSecondOne({
  required BuiltMap<String, dynamic> backupContent,
}) {
  final migratedBackupContent = backupContent.rebuild((backupJson) {
    final collectionsSettingsJson =
        Map.castFrom(backupJson['collections_settings']).map((collectionId, collectionSettingsMap) {
      return MapEntry(collectionId as String, collectionSettingsMap);
    });

    final userCollectionIds = <String>[];

    final userCollectionListItemMaps = List.castFrom(backupJson['user_collection_list_items']);

    for (final userCollectionListItemMap in userCollectionListItemMaps) {
      final userCollectionListItemJson =
          Map.castFrom<dynamic, dynamic, String, dynamic>(userCollectionListItemMap);

      if (userCollectionListItemJson['type'] == 'user_collection') {
        final userCollectionJson = userCollectionListItemJson;

        userCollectionIds.add(userCollectionJson['id']);
      } else if (userCollectionListItemJson['type'] == 'user_collection_group') {
        final userCollectionGroupJson = userCollectionListItemJson;

        final collectionMaps = List.castFrom(userCollectionGroupJson['collections']);

        for (final collectionMap in collectionMaps) {
          final userCollectionJson = Map.castFrom<dynamic, dynamic, String, dynamic>(collectionMap);
          userCollectionIds.add(userCollectionJson['id']);
        }
      }
    }

    const defaultCollectionSettingsJson = {
      'selected': false,
      'high_priority': false,
      'sorting': 'alphabetically',
    };

    for (final userCollectionId in userCollectionIds) {
      collectionsSettingsJson[userCollectionId] =
          collectionsSettingsJson[userCollectionId] ?? defaultCollectionSettingsJson;
    }

    backupJson['collections_settings'] = collectionsSettingsJson;
    backupJson['learning_queue'] = [];
  });

  return migratedBackupContent;
}
